Skip to content

refactor: reduce duplication and simplify codebase#374

Merged
thymikee merged 6 commits into
mainfrom
refactor/reduce-duplication-simplify
Apr 11, 2026
Merged

refactor: reduce duplication and simplify codebase#374
thymikee merged 6 commits into
mainfrom
refactor/reduce-duplication-simplify

Conversation

@thymikee

@thymikee thymikee commented Apr 10, 2026

Copy link
Copy Markdown
Member

Summary

Two-pass refactoring to eliminate unnecessary duplication and simplify the codebase. Net result: -751 lines across 55 files with zero test regressions (all 1237 tests pass).

Pass 1: Mechanical deduplication

Deduplicated identical functions:

  • isEnvTruthy() — was in both retry.ts and session-binding.ts (with .trim() preserved)
  • displayNodeLabel() — was in both output.ts and mobile-snapshot-semantics.ts
  • roundPercent() — was in both android/perf.ts and ios/perf.ts
  • normalizeText() — was in both finders.ts and selectors-match.ts
  • Daemon error construction — identical 7-line block in client.ts and cli.ts

Standardized error responses across ~30 handler files:

  • Added sessionNotFoundResponse() and unsupportedOperationResponse(command) helpers
  • Migrated ~160 inline { ok: false, error: { code, message } } to errorResponse()

Unified handler boilerplate:

  • Extracted mergeParentFlags() replacing identical arrays in batch/replay

Linux tool resolver:

  • createLinuxToolResolver<T>() replacing copy-pasted detection+caching in screenshot/clipboard

Pass 2: Structural simplification

CLI output dispatch (-250 lines):

  • Moved logTailStopper cleanup into try/finally — eliminates 28 duplicate guard calls
  • Extracted writeCommandCliOutput(), writeLogsCliOutput(), writeNetworkCliOutput() from 350-line if/else chain

sanitizeFlags (-57 lines):

  • Replaced 67-line destructure/reconstruct with 10-line pick-from-array loop

Recording finalization (-45 lines):

  • Extracted finalizeRecordingOverlay() replacing 4 copies of telemetry+overlay block across record-trace-ios/android/recording

New files (4)

  • src/daemon-error.tsthrowDaemonError() for client-side daemon response errors
  • src/platforms/perf-utils.tsroundPercent() shared by iOS and Android perf
  • src/platforms/linux/tool-resolver.ts — generic Linux tool resolution with caching
  • src/daemon/handlers/record-trace-finalize.ts — shared recording overlay finalization

Test plan

  • npx tsc --noEmit — zero type errors
  • npm test — all 1237 tests pass (both passes)
  • Verified all formerly-duplicated functions exist in exactly one place
  • PR review feedback addressed: isEnvTruthy preserves .trim() for whitespace-tolerant env parsing

Eliminate copy-pasted functions, inline error boilerplate, and repeated
patterns across daemon handlers and platform modules.

Key changes:
- Deduplicate isEnvTruthy, displayNodeLabel, roundPercent into single sources
- Extract throwDaemonError helper for client/CLI daemon response errors
- Add sessionNotFoundResponse/unsupportedOperationResponse helpers and
  adopt errorResponse() across ~30 handler files (-565 lines)
- Unify BATCH_PARENT_FLAG_KEYS/REPLAY_PARENT_FLAG_KEYS into shared
  mergeParentFlags helper in handler-utils
- Extract createLinuxToolResolver for screenshot/clipboard tool detection
- Remove stale type-sync comments from contracts.ts and metro.ts
@github-actions

github-actions Bot commented Apr 10, 2026

Copy link
Copy Markdown
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-04-11 10:54 UTC

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4814eb7808

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

import { AppError } from './errors.ts';
import type { CliFlags } from './command-schema.ts';
import type { DaemonLockPolicy } from '../daemon/types.ts';
import { isEnvTruthy } from './retry.ts';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve whitespace-tolerant session lock env parsing

Switching session-binding.ts to import isEnvTruthy from retry.ts changes behavior for AGENT_DEVICE_SESSION_LOCKED: the previous local parser used raw.trim().toLowerCase(), but the shared helper only lowercases. Values like ' true ' or ' yes ' now evaluate as false, so resolveLockMode can silently skip the intended 'reject' lock policy in padded/templated env setups that previously worked.

Useful? React with 👍 / 👎.

Bigger wins from restructuring, not just mechanical dedup:

- cli.ts: move logTailStopper to try/finally (eliminates 28 duplicate
  calls), extract writeCommandCliOutput/writeLogsCliOutput/writeNetworkCliOutput
  from 350-line if/else chain, fix remaining throwDaemonError site
- session-store.ts: replace 67-line sanitizeFlags destructure/reconstruct
  with 10-line pick-from-array loop
- record-trace: extract finalizeRecordingOverlay helper, replacing 4
  copies of the telemetry+overlay block across ios/android/recording files
- Deduplicate normalizeText (finders.ts + selectors-match.ts)
- Fix isEnvTruthy to preserve whitespace-tolerant parsing (.trim())
process.exit() does not unwind the stack, so finally blocks are
skipped. Restore explicit logTailStopper() calls before each
process.exit() to prevent leaking the background daemon log tail
process. The finally block remains as a safety net for normal
return paths.

Also refactor writeCommandCliOutput to return an exit code instead
of calling process.exit() directly, keeping the exit decision in
the caller where cleanup is visible.
…cation-simplify

* origin/main:
  test: stabilize android emulator boot tests (#377)
  fix: clean up metro companion workers (#376)
  fix: carry remote-config run id for install-from-source (#375)
@thymikee thymikee merged commit 20021c3 into main Apr 11, 2026
16 checks passed
@thymikee thymikee deleted the refactor/reduce-duplication-simplify branch April 11, 2026 10:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant